package com.mce.nebula.security;

import com.mce.nebula.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;

/**
 * Spring Security用户详情实现
 */
@Data
public class UserDetailsImpl implements UserDetails {
    
    private Long id;
    private String username;
    private String email;
    private String password;
    private boolean active;
    private boolean sysAdmin;
    private String enterpriseId;
    
    public UserDetailsImpl(User user) {
        this.id = user.getId();
        this.username = user.getNickName();
        this.email = user.getEmail();
        this.password = user.getPassword();
        this.active = user.getIsActive() != null && user.getIsActive();
        this.sysAdmin = user.getSysAdmin() != null && user.getSysAdmin();
        this.enterpriseId = user.getEnterpriseId();
    }
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (sysAdmin) {
            return Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }
        return Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
    }
    
    @Override
    public String getPassword() {
        return password;
    }
    
    @Override
    public String getUsername() {
        return username;
    }
    
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    
    @Override
    public boolean isEnabled() {
        return active;
    }
}





